#!/bin/bash

if [ $# -lt 4 ]; then
	echo -e "\n\tSyntax:\t`basename $0` <file to be send> <signatur public-key>	<signatur private-key> <hostname 1> [<hostname 2> ...]\n"
	exit 1;
fi

# extract parameters
FILE=$1;
shift;
PUB_KEY=$1;
shift;
PRIV_KEY=$1;
shift;
HOSTS=("$@");
LAST=$(( ${#HOSTS[@]} - 1 ));

# sign the message
openssl smime -sign -signer $PUB_KEY -inkey $PRIV_KEY -in $FILE > $FILE.send

# iterate over hosts in reverse
for ((i=$LAST; i >= 0 ; i--))
do
	# move temp file
	mv $FILE.send $FILE.temp 2> /dev/null
	# append TO-header if this isn't the final recipient
	if [ $i != $LAST ]; then
		ARG="-to ${HOSTS[$i + 1]} ";
	else
		ARG="";
	fi

	openssl smime -encrypt -in $FILE.temp $ARG -aes256 certificates/${HOSTS[$i]}.crt > $FILE.send
done

# remove temp file
rm $FILE.temp
